package cn.didi.feidi.androidorder.io;

import android.util.Log;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.manager.AppManager;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.AppInfo;

/**
 * Created by king on 2017/7/17.
 */

public class FeidiClient {
    private final String TAG = "FeidiClient.TAG";

    private static FeidiClient mSocketClient;

    private final boolean isConnectLocalService = false; // 是否连接本地测试服务器  针对局域网
    //    private String serverAddress = "112.74.129.253";
    private String serverAddress = "172.18.92.153";
    private int serverPort = 9090;


    private static FeidiSocket socket;

    private static List<String> requests = new ArrayList<String>();

    synchronized public static FeidiClient getIntenace() {
        if (mSocketClient == null)
            mSocketClient = new FeidiClient();
        return mSocketClient;
    }


    private FeidiClient() {
        super();
    }

    /**
     * 1、通过地址获取动态指向IP <br />
     * 2、是否连接本地局域服务 如果是将直接读取 IP , PORT <br />
     *
     * @param isLocalService
     * @return
     */
    private void initFeidiClent(String ip, int port, boolean isLocalService) {
        if (!isLocalService) {
            this.serverAddress = ip;
            this.serverPort = port;
            Log.d(TAG, "动态配置信息  [Ip = " + serverAddress + " , Port = " + serverPort + "]");
        } else {
            Log.d(TAG, "本地配置信息  [Ip = " + serverAddress + " , Port = " + serverPort + "]");
        }
    }

    /**
     * 启动连接
     */
    private void startSocket() {
        synchronized (mSocketClient) {
            if (socket != null && socket.isRuning())
                return;

            stopSocket();
            socket = new FeidiSocket("Feidi");
            socket.setConnectionCallback(new FeidiSocket.ConnectionCallback() {
                @Override
                public void onConnect() {
                    if (requests.isEmpty()) {
                        userLogin();
                    } else {
                        Iterator<String> iterator = requests.iterator();
                        while (iterator.hasNext()) {
                            String temp = iterator.next();
                            send(temp);
                        }
                    }
                }

                @Override
                public void onDisconnect() {

                }
            });
            socket.start(OrderApplication.getFeidiMessageHandler(), serverAddress, serverPort);
            Log.d(TAG, "synchronized.ClientSocket.start()!");
        }
    }

    /**
     * 结束连接
     */
    private void stopSocket() {
        if (socket != null) {
            socket.close();
            socket = null;
        }
    }

    public void send(String request) {
        if (socket != null && socket.isRuning()) {
            socket.send(request);
        } else {
            requests.add(request);
            Log.d(TAG, "socket is null or not runing , try to create socket and connect");
            connectService();
        }
    }

    /**
     * 连接服务器,連接成功或失敗,都回調FeidiHandle.session
     */
    public void connectService() {
        AppInfo appInfo = AppManager.getAppInfo();
        if (appInfo == null) {
            Log.e(TAG, "app config not synchronous,this is serious error !");//// TODO: 2017/7/17 第一次开机启动应该获取app信息

            initFeidiClent("1.1.1.1", 0000, true);
        } else {
            initFeidiClent(appInfo.getAddressIp(), Integer.valueOf(appInfo.getAddressPort()), isConnectLocalService);
        }
        startSocket();
    }

    public boolean isRuning() {
        return socket != null && socket.isRuning();
    }

    /**
     * 关闭服务器
     */
    public void closeService() {
        stopSocket();
    }

    /**
     * 用户登录,如果没有绑定就做重新发送,比如请验证码这一块
     */
    public void userLogin() {
        if (UserManager.isBingAccount()) {
            String userId = UserManager.getUserId();
            String token = UserManager.getToken();
            String phone = UserManager.getPhone();
            if (UserManager.defaultValue.equals(phone)) {
                Log.d(TAG, "警告！ 本地用户已绑定账号,但用户手机号码无效[userId = " + userId + "userPhone = " + phone);
                return;
            }
            Log.d(TAG, "开始登录,userPhone = " + phone);
            Map<String, String> data = new HashMap<String, String>();
            data.put("sendId", SendProtocol.CONNECTION_AUTHENTICATION);
            data.put("uid", userId);
            data.put("token", token);
            Gson gson = new Gson();
            String response = gson.toJson(data);
            send(response);
        }
    }
}
